package handler

import (
	"github.com/gin-gonic/gin"
	"strconv"
	"travel-cms/model"
)

func GoodList(c *gin.Context) {
	page, _ := strconv.Atoi(c.Query("page"))
	size, _ := strconv.Atoi(c.Query("size"))
	offset := (page - 1) * size
	var good []model.Good
	model.DB.Offset(offset).Limit(size).Find(&good)
	var total int64
	model.DB.Model(model.Good{}).Count(&total)
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "查询成功",
		"good":  good,
		"total": total,
	})
}

func CreateGood(c *gin.Context) {
	good_name := c.PostForm("good_name")
	good_price, _ := strconv.Atoi(c.PostForm("good_price")) //字符串转整型
	if good_name == "" || good_price == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "商品名称或商品价格不能为空",
		})
		return
	}
	data := model.Good{
		GoodName:  good_name,
		GoodPrice: float64(good_price),
	}
	err := model.DB.Debug().Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "创建失败",
		})
		return
	} else {
		c.JSON(200, gin.H{
			"code": 200,
			"msg":  "创建成功",
		})
		return
	}

}
